package com.example.springblog.controller;


import com.example.springblog.constant.Constants;
import com.example.springblog.model.Result;
import com.example.springblog.model.UserInfo;
import com.example.springblog.service.UserService;
import com.example.springblog.utils.JwyUtils;
import com.example.springblog.utils.SecurityUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @RequestMapping("/login")
    public Result login(String username,String password){
        log.info("接受到参数：username{} password{}",username,password);
        if(!StringUtils.hasLength(username)||!StringUtils.hasLength(password)){
            Result.fail("用户名或密码不能为空");
        }
        UserInfo userInfo=userService.selectByName(username);
        if (userInfo==null){
            return Result.fail("用户不存在");
        }
        if (!SecurityUtils.verify(password,userInfo.getPassword())){
            return Result.fail("密码错误");
        }
        Map<String,Object> claim=new HashMap<>();
        claim.put(Constants.TOKEN_ID,userInfo.getId());
        claim.put(Constants.TOKEN_USERNAME,userInfo.getUserName());
        String token= JwyUtils.genJwtToken(claim);
        return  Result.sucess(token);
    }
    /*
    * 获取当前登录用户的信息
    * */
    @RequestMapping("/getUserInfo")
    public UserInfo getLoginUserInfo(HttpServletRequest request){
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        Integer userId=JwyUtils.getIdByToken(token);
        if(userId==null){
            return null;
        }
        UserInfo userInfo=userService.selectById(userId);
        return userInfo;
    }
    /*
    * 根据博客id获取作者信息
    * */
    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId){

        UserInfo userInfo=userService.getAuthorInfo(blogId);
        return userInfo;
    }
    /*
    * 注册用户信息
    * */
    @RequestMapping("/register")
    public Boolean register(String username,String password,String githubUrl){
        Boolean b=userService.register(username,password,githubUrl);
        return true;
    }
}
